from django.db import models
from django.contrib.auth.models import User
from backend.models.login import GroupModel
from django.db.models.signals import m2m_changed
import logging

logger = logging.getLogger(__name__)
from send.worker import send_worker


class RemindModel(models.Model):
    time = models.DateTimeField('时间', db_index=True)
    notify_time = models.DateTimeField('提醒时间', db_index=True, null=True)
    defer = models.IntegerField('提前提醒分钟', blank=True, default=0)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    remark = models.TextField('备注', default='', blank=True, null=True)
    event = models.TextField('提醒事件', default='', null=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人', related_name='own_reminds')
    done = models.NullBooleanField('状态', default=False,
                                   choices=((False, '未发送'), (True, '已发送'),))
    groups = models.ManyToManyField(GroupModel, verbose_name="组", related_name="remind_groups")

    class Meta:
        ordering = ["-time"]
        db_table = 'time_remind'
        verbose_name = "提醒"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.event


def create_done_list(sender, instance, **kwargs):
    logger.critical("检测到一个提醒的组员变动")
    for group in instance.groups.all():
        for user in group.members.all():
            if not DoneListModel.objects.filter(user=user, remind=instance).exists():
                DoneListModel.objects.create(user=user, remind=instance)
    logger.info("创建完成列表成功")


m2m_changed.connect(create_done_list, sender=RemindModel.groups.through)


class DoneListModel(models.Model):
    done = models.NullBooleanField('状态', default=False,
                                   choices=((False, '未完成'), (True, '已完成'),))
    remind = models.ForeignKey(RemindModel, on_delete=models.CASCADE, verbose_name='提醒', related_name='remind_done')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户', related_name='remind_done')

    class Meta:
        verbose_name = "完成情况"
        verbose_name_plural = verbose_name
